package sf.dsl.example;

import sf.database.dialect.DBDialect;
import sf.database.jdbc.sql.SQLParameter;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * window条件
 */
public class WindowBuilder {
    protected List<WindowOne> windowOneList;

    public WindowBuilder() {
        this.windowOneList = new LinkedList<>();
    }

    public WindowBuilder add(WindowOne windowOne) {
        windowOneList.add(windowOne);
        return this;
    }

    protected void toSql(StringBuilder sb, List<SQLParameter> list, AtomicBoolean mustTableAlias, DBDialect dialect) {
        sb.append(" WINDOW ");
        boolean f1 = false;
        for (WindowOne w : windowOneList) {
            if (f1) {
                sb.append(',');
            }
            f1 = true;
            String alias = w.alias;
            if (dialect != null) {
                alias = dialect.wrapKeyword(alias);
            }
            sb.append(alias).append(" AS (");
            if (w.windowFunction != null) {
                w.windowFunction.windowDefine(sb, list, mustTableAlias, dialect);
            }
            sb.append(')');
        }
    }

    public static class WindowOne {
        protected String alias;

        protected WindowFunction windowFunction;

        public WindowOne(String alias, WindowFunction windowFunction) {
            this.alias = alias;
            this.windowFunction = windowFunction;
            this.windowFunction.windowName = alias;
        }
    }
}
